<template>
    <div class="dashboard-container">
        <!-- 顶部操作栏 -->
        <div class="search">
            <el-form ref="form" :rules="rules" :model="params" label-position="top" size="medium">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="城市">
                            <el-select 
                                filterable 
                                clearable
                                v-model="params.cityId" 
                                placeholder="请选择" 
                                style="width: 100%;"
                                @change="handleChangeCity"
                            >
                                <el-option v-for="item,index in cityList" :key="index" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区县">
                            <el-select 
                                filterable 
                                clearable
                                v-model="params.areaId" 
                                placeholder="请选择" 
                                style="width: 100%;"
                                @change="handleChangeArea"
                            >
                                <el-option v-for="item,index in areaList" :key="index" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="街道" >
                            <el-select clearable filterable v-model="params.streetId" placeholder="请选择" style="width: 100%;">
                                <el-option v-for="item,index in jdList" :key="index" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 操作按钮 -->
        <div class="opt">
            <el-button type="primary" plain @click="handleSearch">
                <i class="el-icon-search"></i>
                查询
            </el-button>
            <el-button type="primary" plain @click="handleImport">
                导入
            </el-button>
            <el-button type="primary" plain @click="handleExport" v-loading="exportLoading">
                导出
            </el-button>
        </div>

        <!-- 内容栏 -->
        <div class="body">
            <!-- 列表 -->
            <el-table :data="list" v-loading="loading" >
                <el-table-column label="ID" prop="id" width="100"></el-table-column>
                <el-table-column label="市" prop="city.name" width="100" ></el-table-column>
                <el-table-column label="区" prop="area.name" width="100"></el-table-column>
                <el-table-column label="街道" prop="street.name" width="120"></el-table-column>
                <el-table-column label="低点" prop="low" ></el-table-column>
                <el-table-column label="高点" prop="high" ></el-table-column>
                <el-table-column label="均值" prop="average" ></el-table-column>
                <el-table-column label="时点" prop="time" ></el-table-column>
                <el-table-column label="最后操作时间">
                    <template slot-scope="{row}">
                        {{ row.createTime }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150px">
                    <template slot-scope="{row}">
                        <el-button type="text" icon="el-icon-edit" @click="handleAdd(row)">编辑</el-button>
                        <el-button type="text" @click="handleHistory(row)" v-if="row.opLog">历史记录</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="page">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="params.pageIndex+1"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="params.pageCount"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </div>

        <!-- 区片价批量导入 -->
        <el-dialog 
            title="区片价批量导入" 
            :visible.sync="dialogVisible" width="500px"
            :close-on-click-modal="false"
            @close="dialogVisible=false"
        >
            <el-form :model="uploadTemp" :rules="rules" ref="form">
                <!-- <el-form-item label="模版">
                    <a :href="OSS_BASE_URL+'common/regionCase.xlsx'" target="__bank"><el-button type="primary">下载</el-button></a>
                </el-form-item> -->
                
                <el-form-item label="导入文件" prop="filePath">
                    <el-upload
                        style="text-align: center;"
                        class="upload-demo"
                        drag
                        :action="API_BASE_URL + '/common/uploadFile'"
                        name="file"
                        :on-success="handleSuccess"
                        :before-upload="handleBefore"
                        :on-error="handleError"
                        :limit="1"
                        accept=".xlsx"
                    >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传xlsx文件</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div class="opt_btn" style="padding-top: 30px;" >
                <el-button type="primary" @click="handleSubmitUpload('form')" :loading="uploadLoading">提交</el-button>
                <el-button type="primary" @click="dialogVisible=false" plain>取消</el-button>
            </div>
        </el-dialog>

        <!-- 编辑区片价 -->
        <el-dialog 
            title="编辑区片价" 
            :visible.sync="dialogVisibleUpdate" width="500px"
            :close-on-click-modal="false"
            @close="dialogVisible=false"
        >
            <el-form :model="temp" ref="form">
                <el-form-item label="平均值(万元/亩)">
                    <el-input placeholder="请输入" v-model="temp.average"></el-input>
                </el-form-item>
                <el-form-item label="高点(万元/亩)">
                    <el-input placeholder="请输入" v-model="temp.high"></el-input>
                </el-form-item>
                <el-form-item label="低点(万元/亩)">
                    <el-input placeholder="请输入" v-model="temp.low"></el-input>
                </el-form-item>
            </el-form>
            <div class="opt_btn" style="padding-top: 30px;" >
                <el-button type="primary" @click="handleSubmitUpdate" :loading="uploadLoading">提交</el-button>
                <el-button type="primary" @click="dialogVisibleUpdate=false" plain>取消</el-button>
            </div>
        </el-dialog>

         <!-- 历史记录列表 -->
         <el-dialog 
            title="历史记录" 
            :visible.sync="dialogVisibleLog" width="500px"
            :close-on-click-modal="false"
            @close="dialogVisible=false"
        >
            <el-table :data="logList">
                <el-table-column label="操作时间" prop="createTime"></el-table-column>
                <el-table-column label="操作内容" prop="log"></el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="page">
                <el-pagination
                    @size-change="handleSizeChangeLog"
                    @current-change="handleCurrentChangeLog"
                    :current-page="logParams.pageIndex+1"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="logParams.pageCount"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="logTotal">
                </el-pagination>
            </div>
            <div class="opt_btn" style="padding-top: 10px;" >
                <el-button type="primary" @click="dialogVisibleLog=false" plain>关闭</el-button>
            </div>
        </el-dialog>
        
    </div>
</template>

<script> 
import { regionPriceGetList, regionPriceImportXlsx, regionPriceUpdate } from '@/api/region'
import { commonGetAreaList, commonGetCityList } from '@/api/common'
import { transfromData,transFormValue } from '@/utils/tools';
import { geoTypeList, API_BASE_URL, OSS_BASE_URL } from '@/utils/common'
import axios from 'axios'
import moment from 'moment'
import { operationLogGetList } from '@/api/log'

export default {
    name: 'regionPrice',
    data(){
        return {
            API_BASE_URL,
            geoTypeList,
            OSS_BASE_URL,
            rules: {
                type: [{ required: true, message: '请选择案例对象', trigger: 'blur' }],
                filePath: [{ required: true, message: '请上传导入文件', trigger: 'blur' }],
            },
            params: {
                provinceId: 11,  //默认浙江省
                cityId: '', //城市id
                areaId: '',// 区县id
                streetId: '', //街道id
                propertyType: 102,
                pageIndex: 0,
                pageCount: 10,
            },
            cityList: [],
            areaList: [],
            jdList: [],
            loading: false,
            list: [],
            total: 0,
            cityListLabel: [],
            dialogVisible: false,
            uploadLoading: false,
            uploadTemp: {
                filePath: '',
                coverFlag: 1,
                propertyType: 102
            },
            multipleSelection: [],
            exportLoading: false,
            dialogVisibleUpdate: false,
            temp: {},
            logParams: {
                objectIds: '',
                pageCount: 10,
                pageIndex: 0
            },
            logTotal: 0,
            dialogVisibleLog: false,
            logList: []
        }
    },
    async mounted(){
        let data = await commonGetCityList({ geoLevel: 2, provinceId: 11 });
        this.cityList = data;
        this.cityListLabel = data.map(item=>{
            return { label: item.name, value: item.id }
        })
        this.handleSearch();
    },
    methods:{
        //历史记录
        handleHistory(row){
            this.dialogVisibleLog = true
            this.logParams.pageIndex = 0;
            this.logParams.objectIds = [row.id]
            this.getLogList();
        },
        //获取日志列表
        async getLogList(){
            let data = await operationLogGetList(this.logParams)
            this.logList = data.list.map(item=>{
                //解析操作的内容
                let params = JSON.parse(item.objectValue);
                let str = '';
                for(let key in params){
                    if(key=='low'){
                        str+='低点：'+params[key] + ';'
                    }
                    if(key=='high'){
                        str+='高点：'+params[key] + ';'
                    }
                    if(key=='average'){
                        str+='均值：'+params[key] + ';'
                    }
                }
                item.log = str;
                item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
                return item;
            })
            this.logTotal = data.totalCount;
        },
        //提交编辑
        async handleSubmitUpdate(){
            this.uploadLoading = true;
            await regionPriceUpdate(this.temp);
            this.uploadLoading = false;
            this.$message.success({message: '修改成功'})
            this.dialogVisibleUpdate = false;
            this.handleSearch();
        },
        //点击编辑
        handleAdd(row){
            this.dialogVisibleUpdate = true;
            this.uploadLoading = false;
            this.temp = {
                id: row.id,
                average : row.average ,
                high: row.high ,
                low: row.low
            }
        },
        //导出区片价
        async handleExport(){
            this.exportLoading = true
            let params = JSON.parse(JSON.stringify(this.params));
            axios({
                url: `${API_BASE_URL}/regionPrice/export${transFormValue(params)}`,
                method: 'POST',
                responseType: 'blob'
            }).then((res) => {
                const blob = res.data
                const fileName = moment().format('YYYY-MM-DD') + '区片价导出.xlsx'
                const elink = document.createElement('a')
                elink.download = fileName
                elink.style.display = 'none'
                elink.href = window.URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                window.URL.revokeObjectURL(elink.href)// 释放对象
                document.body.removeChild(elink)// 移除元素
                this.exportLoading = false
            })
        },
        //上传失败
        handleError(){
            this.uploadLoading = false;
        },
        //上传前钩子
        handleBefore(){
            this.uploadLoading = true;
        },
        // 上传成功
        handleSuccess(res, file){
            this.uploadTemp.filePath = res.data
            this.uploadLoading = false;
        },
        // 点击提交
        handleSubmitUpload(formName){
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    await regionPriceImportXlsx(this.uploadTemp)
                    this.$message.success({ message: '提交成功' })
                    this.dialogVisible = false;
                }else {
                    console.log('error submit!!');
                    return false;
                }
            });  
        },
        // 点击导入
        handleImport(){
            this.uploadTemp = {
                propertyType: 102,
                filePath: '',
                coverFlag: 1
            }
            this.dialogVisible = true;
        },
        //修改搜索条件
        handleSearch(){
            this.params.pageIndex = 0;
            this.getData();
        },
        //选择了区县
        async handleChangeArea(val){
            if(val){
                this.jdList = this.areaList.filter(item=>item.id==val)[0].streets;
            }else{
                this.jdList = [];
            }
            
            this.params.streetId = '';
        },
        //改变城市
        async handleChangeCity(val){
            if(val){
                // 请求区县信息
                let data = await commonGetAreaList({ geoLevel: 4, cityId: val })
                this.areaList = data;
            }else{
                this.areaList = [];
            }
            //清空之前的区县选择
            this.params.areaId = '';
            this.params.streetId = '';
            
        },
        //加载列表数据
        async getData(){
            this.loading = true
            let data = await regionPriceGetList(this.params)
            this.loading = false;
            this.total = data.totalCount;
            this.list = data.list.map(item=>{
                item.cityName = transfromData(this.cityListLabel, item.cityId)
                item.time = moment(item.time).format('YYYY-MM-DD')
                item.createTime = item.opLog?moment(item.opLog.createTime).format('YYYY-MM-DD HH:mm:ss'):''
                return item;
            });
        },
        // 修改每页数量
        handleSizeChange(val){
            this.params.pageIndex = 0;
            this.params.pageCount = val;
            this.getData();
        },
        // 切换分页
        handleCurrentChange(val){
            this.params.pageIndex = val - 1;
            this.getData();
        },
        // 修改每页数量
        handleSizeChangeLog(val){
            this.logParams.pageIndex = 0;
            this.logParams.pageCount = val;
            this.getLogList();
        },
        // 切换分页
        handleCurrentChangeLog(val){
            this.logParams.pageIndex = val - 1;
            this.getLogList();
        }
    }
}
</script>
<style lang="scss" scoped>
.dashboard {
    &-container {
      margin: 30px;
      position: relative;
      .opt{
        margin-bottom: 10px;
      }
      .page{
        padding: 20px 0;
        text-align: center;
      }
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
}
</style>
  